package craky.keeper.server;

import org.eclipse.jetty.server.Server;

import android.app.IntentService;
import android.content.Intent;
import craky.keeper.KeeperServer;
import craky.keeper.util.Util;
import craky.keeper.util.Util.ServiceActionResult;

public class KeeperService extends IntentService
{
    public static boolean stopNormal;

    private KeeperServer keeperServer;

    private boolean copyFileError;

    public KeeperService()
    {
        super("KeeperService");
        setIntentRedelivery(true);
        this.keeperServer = KeeperServer.getInstance();
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        Boolean result = Util.copyFiles(getBaseContext());

        if(result == null || result.booleanValue())
        {
            Server server = keeperServer.start(Util.getCustomPort(), Util.keeperDataParentPath, false);

            if(server == null)
            {
                stopWhenStartFaild(ServiceActionResult.Start_Exception);
            }
            else
            {
                sendResult(ServiceActionResult.Start_OK);

                try
                {
                    server.join();
                }
                catch(Exception e)
                {
                    stopWhenStartFaild(ServiceActionResult.Start_Exception);
                }
            }
        }
        else
        {
            copyFileError = true;
            stopWhenStartFaild(ServiceActionResult.Copy_File_Error);
        }
    }

    private void stopWhenStartFaild(ServiceActionResult result)
    {
        stopNormal = true;
        stopSelf();
        sendResult(result);
    }

    @Override
    public void onDestroy()
    {
        if(copyFileError)
        {
            copyFileError = false;
        }
        else
        {
            try
            {
                keeperServer.stop();
                sendResult(ServiceActionResult.Stop_OK);
            }
            catch(Exception e)
            {
                stopNormal = true;
                sendResult(ServiceActionResult.Stop_Exception);
            }
        }

        super.onDestroy();

        if(!stopNormal)
        {
            startService(new Intent(this, this.getClass()));
        }
        else
        {
            stopNormal = false;
        }
    }

    private void sendResult(ServiceActionResult result)
    {
        Intent intent = new Intent(Util.MESSAGE_KEY);
        intent.putExtra(Util.SERVICE_ACTION_RESULT_KEY, result.toString());
        getBaseContext().sendBroadcast(intent);
    }
}